<?php
namespace App\Library;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

class Log
{
    public static $_fileName;
    public static $_type;
    // 所有的LOG都要求在这里注册
    const LOG_ERROR = 'error';
    const LOG_INFO = 'info';
    const LOG_WARNING = 'warning';

    public static $loggers = array(
        //'error'     =>  400 ,
        //'notice'    => 250,
        'warning'   => 300,
        'info'      => 200,
    );

    public function __construct(Request $request)
    {
    }


    /**
     * @param $message
     * @param array $data
     * @param string $filename
     * @param string $type 类型
     */
    private static function _save($message, $data = [], $filename = 'log',$type = self::LOG_INFO)
    {
        date_default_timezone_set('PRC'); //设置时区为北京时区
        if (PHP_SAPI == 'cli') {
            // 脚本命令日志
            $filename .= '_cli';
            $traceId = CLI_REQUEST_ID;
            self::_write($traceId,$filename,$data,$message,$type);
        } else {
            $traceId = REQUEST_ID;
            if ($type == self::LOG_INFO) {
                $filename = 'info';
            }
            if ($type == self::LOG_WARNING) {
                $filename = 'warning';
            }
            self::_write($traceId,$filename,$data,$message,$type);
        }
    }

    /**
     * @param $traceId
     * @param $filename
     * @param $data
     * @param $message
     * @param $type
     * @throws \Exception
     */
    protected static function _write($traceId,$filename,$data,$message,$type) {
        $log = new Logger($traceId);
        $path = '/data/logs/xsj_user_platform_sync_project';
        #$path = '/Users/chenliumeng/data/xsj_user_platform_sync_project';
        // 日志权限
        self::mkDirs($path);
        $path = $path . '/' . $filename.date('Ymd').'.log';
        if (gettype($data) != 'array') {
            $message .= "：" . $data;
            $data = [];
        }
        $level = isset(self::$loggers[$type]) ? self::$loggers[$type] : 200;
        $log->pushHandler(new StreamHandler($path, $level));
        $log->addRecord($level,$message, $data);
    }

    /**

     * @param $message
     * @param array $data
     * @param string $filename
     */
    public static function logInfo($message, $data = [], $filename = 'info')
    {
        self::_save($message, $data, $filename,'info');
    }

    /**
     * @param $message
     * @param array $data
     * @param string $filename
     * @param string $type
     */
    public static function logWarning($message, $data = [], $filename = 'warning',$type = 'warning')
    {
        self::_save($message, $data, $filename,$type);
    }


    /**
     * 给日志文件夹权限
     * @param $dir
     * @param int $mode
     * @return bool
     */
    public static function mkDirs($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode,true)) {
            return TRUE;
        }
        if (!self::mkdirs(dirname($dir), $mode)) {
            return FALSE;
        }
        return @mkdir($dir, $mode,true);
    }

    /**
     * @param string $type
     * @param string $fileName
     */
    public static function sql($type = self::LOG_INFO,$fileName ='laravel')
    {
        self::$_fileName = $fileName;
        self::$_type = $type;
        DB::listen(function ($sql) {
            //$fileName = $fileName;
            foreach ($sql->bindings as $i => $binding) {
                if ($binding instanceof \DateTime) {
                    $sql->bindings[$i] = $binding->format('Y-m-d H:i:s');
                } else {
                    if (is_string($binding)) {
                        $sql->bindings[$i] = "'$binding'";
                    }
                }
            }
            $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
            $query = vsprintf($query, $sql->bindings);
            $time = $sql->time;
            if (self::$_type == self::LOG_INFO && $time < 1) {
                self::logInfo('info.sql',['sql' => $query,'exec_time' => $time]);
            } else{
                self::logWarning('warning.sql',['sql' => $query,'time' => $time]);
            }
        });
    }

}
